package com.navinfo.opentsp.qingqi.trackoptimize.common.validation;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by Administrator on 2016/3/4.
 */
public class ValidateUtil {

    public static String validateCommand(Object obj, Class... groups) {
        String message = null;//用于存储验证后的错误信息

        Validator validator = Validation.buildDefaultValidatorFactory()
                .getValidator();

        Set<ConstraintViolation<Object>> constraintViolations = validator
                .validate(obj, groups);//验证某个对象,，其实也可以只验证其中的某一个属性的

        Iterator<ConstraintViolation<Object>> iter = constraintViolations
                .iterator();
        while (iter.hasNext()) {
            String tempMessage = iter.next().getMessage();
            if(tempMessage != null && tempMessage.length() > 0)
            {
                message = tempMessage;
                break;
            }
        }

        return message;
//        StringBuffer buffer = new StringBuffer();//用于存储验证后的错误信息
//
//        Validator validator = Validation.buildDefaultValidatorFactory()
//                .getValidator();
//
//        Set<ConstraintViolation<Object>> constraintViolations = validator
//                .validate(obj);//验证某个对象,，其实也可以只验证其中的某一个属性的
//
//        Iterator<ConstraintViolation<Object>> iter = constraintViolations
//                .iterator();
//        while (iter.hasNext()) {
//            String message = iter.next().getMessage();
//            buffer.append(message);
//            buffer.append("\r\n");
//        }
//        return buffer.toString();
    }
}
